// @/composables/useTableActions.ts
// @/composables/useRemoveRow.ts
import { VxeUI } from "vxe-pc-ui";
import { ElMessage } from "element-plus";
import { delEntityById } from "@/api"; 

// 通用图标映射（与数据结构无关）
const ICON_MAP: Record<string, string> = {
  edit: "vxe-icon-edit",
  del: "vxe-icon-delete",
  delete: "vxe-icon-delete",
  view: "vxe-icon-view",
  addchild: "vxe-icon-add",
  add: "vxe-icon-add",
  child:"vxe-icon-add",
  setmenu: "vxe-icon-setting",
  copy: "vxe-icon-copy",
  export: "vxe-icon-export",
  import: "vxe-icon-import",
  refresh: "vxe-icon-refresh",
};

// 定义一个通用类型 T，代表任意行数据结构
export function useTableActions<T = Record<string, any>>(customHandlers: Handlers<T> = {}) {
  const handlers: Handlers<T> = { ...DEFAULT_HANDLERS, ...customHandlers };

  const getButtonIcon = (code: string): string => {
    return ICON_MAP[code.toLowerCase()] || "";
  };

  const handleRowAction = (code: string, row: T, extra: any = {}) => {
    const action = code.toLowerCase();
    if (handlers[action]) {
      handlers[action](row, extra);
    } else {
      ElMessage.info(`操作 "${code}" 未实现`);
    }
  };

  return {
    getButtonIcon,
    handleRowAction,
  };
}

// === 类型定义区 ===
type Handler<T = any> = (row: T, extra?: any) => void;
type Handlers<T = any> = Record<string, Handler<T>>;

// 默认处理器使用泛型 T
const DEFAULT_HANDLERS: Handlers = {
  edit: (row, extra) => {
    const { openEditPopup } = extra || {};
    if (openEditPopup) {
      openEditPopup(row);
    } else {
      console.warn("edit 操作未传入 openEditPopup 回调");
    }
  },
  del: (row, extra) => {
    const { removeRow } = extra || {};
    if (removeRow) {
      removeRow(String((row as any).id));
    } else {
      console.warn("del 操作未传入 removeRow 回调");
    }
  },
  addchild: (row, extra) => {
    const { addChildMenu } = extra || {};
    if (addChildMenu) {
      addChildMenu(row);
    } else {
      ElMessage.warning("暂未实现：添加子部门");
    }
  },
  child: (row, extra) => {
    const { addChildMenu } = extra || {};
    if (addChildMenu) {
      addChildMenu(row);
    } else {
      ElMessage.warning("暂未实现：添加子部门");
    }
  },
  setmenu: (row, extra) => {
    const { handleSetting } = extra || {};
    if (handleSetting) {
      handleSetting((row as any).id);
    } else {
      ElMessage.warning("暂未实现：设置菜单");
    }
  },
  view: (row) => {
    ElMessage.info(`查看数据`);
  },
  copy: (row) => {
    ElMessage.success("复制成功");
  },
};



export function useRemoveRow(
  moduleType: string | (() => string), // 模块类型，可以是字符串或函数
  refreshFn: () => void                // 刷新函数
) {
  const removeRow = (id: string) => {
    VxeUI.modal.confirm({
      title: "提示",
      content: "确定删除数据吗？",
      mask: false,
      lockView: false,
      onConfirm: async () => {
        try {
          // 获取当前模块类型
          const type = typeof moduleType === "function" ? moduleType() : moduleType;
          
          const res = await delEntityById(type, { ids: id });
          
          if (res.code === 0) {
            ElMessage.success("删除成功");
            refreshFn(); // 刷新数据
          } else {
            ElMessage.error(res.message || "删除失败");
          }
        } catch (err: any) {
          ElMessage.error(err.message || "请求失败");
        }
      },
    });
  };

  return {
    removeRow,
  };
}

export function setupToolbar(permissions: any[]) {
      const toolImport: { import?: boolean } = {};
      const toolExport: { export?: boolean } = {};
      const buttons: any[] = [];

      permissions.forEach((item) => {
        if (item.name === "导入") {
          toolImport.import = true;
        } else if (item.name === "导出") {
          toolExport.export = true;
        } else {
          buttons.push(item);
        }
      });

      return {
        buttons,
        ...toolImport,
        ...toolExport,
        custom: true,
        print: true,
      };
    }